package service

import (
	"context"
	"gitee.com/WisdomClassroom/core"
	"gitee.com/WisdomClassroom/core/models"
	"gitee.com/WisdomClassroom/core/protobufs/v1/pb"
	"gitee.com/WisdomClassroom/question/glb"
	"google.golang.org/grpc/metadata"
)

func (s *Service) AnswerQuestion(ctx context.Context, request *pb.AnswerQuestionRequest) (*pb.AnswerQuestionResponse, error) {
	md, ok := metadata.FromIncomingContext(ctx)
	if !ok {
		glb.Logger.Error("no metadata")
	}
	token, err := core.UnpackTokenFromMetadata(md)
	if err != nil {
		return &pb.AnswerQuestionResponse{Status: &pb.ResponseStatus{
			Code: core.ResponseStatusCodeNotAuth, Message: err.Error(),
		}}, nil
	}

	if token.Type != core.UserTypeStudent {
		return &pb.AnswerQuestionResponse{Status: &pb.ResponseStatus{
			Code:    core.ResponseStatusCodeNotAuth,
			Message: "仅学生能调用此接口",
		}}, nil
	}

	questionAnswer := &models.QuestionAnswer{
		StudentID:    token.AccountID,
		UsedTime:     request.UsedTime,
		QuestionUUID: request.GetQuestionUUID(),
		IsCorrect:    request.GetIsCorrect(),
	}

	err = glb.DB.Create(questionAnswer).Error
	if err != nil {
		if core.IsForeignKeyErr(err) {
			return &pb.AnswerQuestionResponse{Status: &pb.ResponseStatus{
				Code:    core.ResponseStatusCodeOtherError,
				Message: "学生不存在",
			}}, nil
		}
		glb.Logger.Error(err.Error())
		return answerQuestionRespSvrErr, nil
	}

	return &pb.AnswerQuestionResponse{
		Status: &pb.ResponseStatus{Code: core.ResponseStatusCodeSuccess},
	}, nil
}
